package com.xzcedu.homework;

import org.junit.jupiter.api.Test;

import java.io.*;

/**
 * @author 徐州城
 * @version 1.0
 * 要求：使用BufferedReader 读取一个文本文件，为每行加上行号，
 * 再连同内容一并输出到屏幕上.
 * <p>
 * 如果把文件的编码 改成了 gbk，出现中文乱码，思考如何解决
 * 1. 默认是按照uft-8 处理，不会乱码
 * 2. 提示：使用转换流，将 FileInputStream -> InputStreamReader -> bufferStreamReader
 */
public class Homework02 {
    public static void main(String[] args) throws IOException {

        String fileName = "e:\\f1.txt";

        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileName));
        //需要一行一行的读
        String line = "";
        int i = 1;

        while ((line = bufferedReader.readLine()) != null) {//当为null时 表示已经读完了
            System.out.println((i++) + " " + line);
        }

        bufferedReader.close();
    }

    /**
     * 如果把文件的编码 改成了 gbk，出现中文乱码，思考如何解决
     * 1. 默认是按照uft-8 处理，不会乱码
     * 2. 提示：使用转换流，将 FileInputStream -> InputStreamReader -> bufferStreamReader
     */
    @Test
    public void test1() {
        String fileName = "e:\\f1.txt";
        String charSet = "gbk";

        BufferedReader br = null;

        try {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(fileName), charSet);//指定编码
            br = new BufferedReader(isr);
            int count = 0;
            String line = "";

            while ((line = br.readLine()) != null) {
                System.out.println((++count) + " " + line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            if (br != null){

                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
